import os, sys
import subprocess
import time
from subprocess import Popen
import pretty_write

class Experiment:

    def __init__(self, num_clients, time):
        self.process_list = []
        self.num_clients = 12
        self.time = time / 5
        self.file_size = "_small"
        self.request_rate_agg = 0

    def run(self):
        int_count = 1
        for j in range(0,self.time):
            request_rate = 0
            for i in range(0,self.num_clients):
                self.process_list.append(Popen(["python", "webserver.py", "10", "%s"%self.file_size], stdout=subprocess.PIPE))
            top = self.num_clients
            if j >= 18:
                for i in range(0,self.num_clients):
                    self.process_list.append(Popen(["python", "webserver.py", "10", "_reallylongnameblahblah"], stdout=subprocess.PIPE))
                top = self.num_clients * 2
            for i in range(0,top):
                self.process_list[i].wait()
                strings = self.process_list[i].stdout.readlines()
                request_rate += float(strings[0])
            self.process_list = []
            self.request_rate_agg += request_rate
            print "%d\t%.02f\t%.02f"%((j+1)*5, request_rate,(self.request_rate_agg / (int_count)))
            #print "%d(%d): %.02f(%.02f)"%(self.num_clients, (1+j), (self.request_rate_agg / (j+1)), (request_rate))
            #time.sleep(2)
            int_count += 1
            
            

    def getResult(self):
        return self.request_rate_agg / self.time
        
if __name__ == '__main__' :

    num_procs = [16]
    load = [100]
    results = {}
    ret = 0
    
    for i in num_procs:
        #ret = os.system('ssh root@pc22 "cd attack; ./makesys.sh %d attack && make -j" > /dev/null 2>> ./error.log'%i)
        if(ret == 0):
            print "Make with %d processors succeeded."%i
        line = []
        for j in load:
            ret = os.system('ssh pc22 "cd classify; screen -d -m ./classify"')
            if(ret == 0):
                print "Execution of attack succeeded for load %d."%j
            else:
                exit("Execution failed with load %d."%j)
            time.sleep(5)
            exp = Experiment(j, 180)
            exp.run()
            line.append(exp.getResult())
            ret = os.system('ssh pc22 "killall -9 classify"')
            if(ret == 0):
                print "Successfully killed classify for load %d."%j
            else:
                exit("Kill failed with load %d."%j)
        results[i] = line
    
#    pretty = pretty_write.Pretty("attack_load.dat", load, num_procs, results)
#    pretty.writeOut()
#    pretty.printOut()



